package com.kason.classloader;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author Kason
 * @date 2020/10/13 14:36
 */
public class KasonClassloader extends ClassLoader{

    /**
     * 实现自定义加载器的步骤：
     * 1.实现ClassLoader接口
     * 2.重写超类的findClass方法
     * @param name
     * @return
     * @throws ClassNotFoundException
     */

    @Override
    public Class<?> findClass(String name) throws ClassNotFoundException {

        String fileName = name.substring(name.lastIndexOf(".") + 1) + ".class";
        InputStream is = getClass().getResourceAsStream(fileName);
        if (is !=null) {
            byte[] b = new byte[0];
            try {
                b = new byte[is.available()];
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                is.read(b);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return defineClass(name, b, 0, b.length);

        }

        return null ;
    }

    /**
     * 自定义类加载器，与AppClassLoader加载类的区别
     * 分别存储在不同的堆空间中
     *
     * @param args
     * @throws ClassNotFoundException
     * @throws IllegalAccessException
     * @throws InstantiationException
     */
    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        KasonClassloader kasonClassloader = new KasonClassloader();
        Class<?> aClass1 = kasonClassloader.loadClass(TestClassLoader.class.getName());
        System.out.println(aClass1.hashCode());
        System.out.println(aClass1.getClassLoader());

        Class<?> aClass2 = kasonClassloader.findClass(TestClassLoader.class.getName());
        System.out.println(aClass2.hashCode());
        System.out.println(aClass2.getClassLoader());

        boolean x1 = aClass1.newInstance() instanceof TestClassLoader;
        System.out.println(x1);

        boolean x2 = aClass2.newInstance() instanceof TestClassLoader;
        System.out.println(x2);
        System.out.println(TestClassLoader.class.getClassLoader());

    }







}
